<?php

/*
*/

class Stock_advice_stock_model extends CI_Model
{

	static $TABLE;
	public $error;

	function __construct()
	{
		parent::__construct();
		//载入库文件
		$this->load->library('test_database');
		$this->test_database->test();
		//载入核心类
		$this->load->database($this->test_database->get_db());
		//初始化
		$this->TABLE = 'stock_advices_stocks';
		//临时表
		$this->TEMP_TABLE = 'temp_' . $this->TABLE;
		//模式
		$this->mode = FALSE;
		//初始化错误
		$this->error = FALSE;
	}

	function create_stock($stock_advice_id, $sub_goods_stock)
	{
		$this->load->model('Sub_goods_model');
		//所有仓库的ID
		$store_ids = array(1,2);
		//所有子货物
		$all_sub_goods = $this->Sub_goods_model->get_all();
		foreach ($all_sub_goods as $as_goods)
		{
			$data = array(
				'stock_advice_id'	=> $stock_advice_id,
				'sub_goods_id'		=> $as_goods->sub_goods_id,
				'create_date'		=> time()
				);
			//遍历所有仓库
			foreach ($store_ids as $key=>$stock_id)
			{
				$data['store_id'] = $stock_id;
				if (isset($sub_goods_stock[$as_goods->sub_goods_id]))
				{
					if(isset($sub_goods_stock[$as_goods->sub_goods_id]['quantities'][$stock_id]))
					{
						$data['quantity'] = $sub_goods_stock[$as_goods->sub_goods_id]['quantities'][$stock_id];
					}
					else
					{
						$data['quantity'] = 0;
					}
				}
				else
				{
					$data['quantity'] = 0;
				}

				//结算库存时，子货物任何一个仓库数量不能为负数
				if ($data['quantity'] < 0)
				{
					//$this->error = 'CANNOT_BALANCE_LESS_THEN_0';
					//return FALSE;
				}

				if (!$this->db->insert($this->TABLE, $data))
				{
					$this->error = 'CANNOT_INSERT_ADVICE_STOCK';
					return FALSE;
				}
			}
		}
		return TRUE;
	}

	//$in_key[boolean] : 将sub_goods_id存入数组key中
	function get_stock($stock_advice_id, $id_in_key=FALSE)
	{
		$advice_stocks = array();	//初始化容器

		$this->db->where('stock_advice_id = ' . $stock_advice_id);
		$query = $this->db->get($this->TABLE);
<<<<<<< HEAD
		
=======

>>>>>>> ff5f7ef6de592146b376adc8ed0c004b06507151
		if ($query->num_rows() > 0)
		{
			$advice_stocks = $query->result();
		}

		if ($id_in_key)
		{
			$advice_stocks_ = array();	//初始化新的容器
			foreach ($advice_stocks as $stock)
			{
				if (!isset($advice_stocks_[$stock->sub_goods_id][$stock->store_id]))
				{
					$advice_stocks_[$stock->sub_goods_id][$stock->store_id] = $stock->quantity;
				}
			}
			return $advice_stocks_;
		}
		else
		{
			return $advice_stocks;
		}
	}

	//获取一个子获取的所有仓库库存
	function get_single_stocks($stock_advice_id, $sub_goods_id)
	{
		$this->db->where('stock_advice_id = ' . $stock_advice_id);
		$this->db->where('sub_goods_id = ' . $sub_goods_id);
		$this->db->select('store_id, quantity');
		return $this->db->get($this->TABLE)->result_array();
	}

}